package org.example.notificationservice.sender;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.notificationservice.entity.Notification;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;

@Slf4j
@Component
@RequiredArgsConstructor
public class EmailNotificationSender implements NotificationSender {
    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    @Override
    public void send(Notification notification) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            String recipientEmail = notification.getMetadata().get("email").toString();
            helper.setTo(recipientEmail);
            helper.setSubject(notification.getTitle());

            // 使用Thymeleaf模板引擎处理邮件内容
            Context context = new Context();
            context.setVariables(notification.getMetadata());
            String emailContent = templateEngine.process("mail/" + notification.getMetadata().get("template"), context);
            helper.setText(emailContent, true);

            mailSender.send(message);
            log.info("Email sent successfully to: {}", recipientEmail);
        } catch (Exception e) {
            log.error("Failed to send email notification", e);
            throw new RuntimeException("Failed to send email notification", e);
        }
    }

    @Override
    public boolean supports(Notification.NotificationType type) {
        return Notification.NotificationType.EMAIL.equals(type);
    }
}